let CFG = require('../config');
let tbDevice = require('../model/tb_device');
let tbLog = require('../model/tb_log');
let rCache = require('../model/redis_cache');
let timLib = require('../comm/time-lib');
let FUN = require('../comm/func');

//缓存初始化
function Init()
{
  rCache.delNode(rCache.N_Config);
  tbLog.cleanByStamp(7*86400*1000);
}

//处理默认过期时间
function DevExpireHandler(Record)
{
  if(!Record.first)
  {
    Record.first=timLib.CurrDateStr(0);
    tbDevice.updateDev(Record.hwid, {first:Record.first});
  }
  if(!Record.expire)
  {
    Record.expire=timLib.CurrDateStr(CFG.USER_VAILD_EXPIRE);
    tbDevice.updateDev(Record.hwid, {expire:Record.expire});
  }
}

//一级设备上线处理
function Dev_Online(Hwid,Ip)
{
  let TimStr=timLib.NowStr();
  let TypeName = FUN.Hwid2TypeName(Hwid);

  if( TypeName!=CFG.T_Gw &&
      TypeName!=CFG.T_Wpass &&
      TypeName!=CFG.T_Dtu
      ) return;

  tbDevice.find(Hwid).then((Record)=>{
    if(Record) //有本设备的记录
    {
      tbDevice.online(Hwid, Ip);
      tbLog.newDevLog(Record.uid, Hwid, 1000, FUN.Hwid2TypeName(Hwid)+' online', timLib.NowStamp());
      DevExpireHandler(Record);

      let config={'uid':Record.uid,'hwid':Hwid,'expire':timLib.Str2Stamp(Record.expire),'mode':Record.mode};
      rCache.set(rCache.N_Config,Hwid,config); // 记录过期日期到缓存中

      console.log('Online', FUN.Hwid2TypeName(Hwid)+':', parseInt(Hwid), TimStr);
    }
    else //数据库没有本设备记录
    {
      let NowTim=timLib.NowStamp();
      let DevType=Hwid2TypeNum(Hwid);

      tbLog.newDevLog(0, Hwid, 1003, FUN.Hwid2TypeName(Hwid)+' unreg', timLib.NowStamp());
      console.log('Unreg '+FUN.Hwid2TypeName(Hwid)+':', Hwid,TimStr);
      // let config={'hwid':Hwid,'expire':NowTim+365*24*3600000};
      // rCache.set(rCache.N_Config,Hwid,config);//记录过期日期到缓存中
      // dbDev.newDev(Hwid,DevType,Ip).then((insertId)=>{
      //   dbDev.online(Hwid,Ip);
      // })

      return;
    }

    if(TypeName==CFG.T_Dtu) //dtu直接记录信息
    {
      rCache.set(rCache.N_Config,Hwid,{'hwtype':CFG.HwType.indexOf('dtu'),'project':'0','brother':0});
    }
    else //主动向设备索取config
    {
      require('./devConfig').SendConfigCmd(Hwid);
    }

  })//end find
}

//连接下线处理
//供amqp使用，wdev不用这个
function Dev_Offline(Hwid)
{
  let TimStr=timLib.NowStr();
  //console.log('Dev_Offline',Hwid);

  tbDevice.find(Hwid).then((Record)=>{  //找出数据库记录
    if(Record){
      rCache.del(rCache.N_Config,Record.hwid);//删除配置记录
      tbDevice.offline(Record.hwid,Record.hwtype==CFG.HwType.indexOf('wdev')?true:false).then((affectNum)=>{//wdev保留conn id
        tbLog.newDevLog(Record.uid,Record.hwid,
          (Record.hwtype==CFG.HwType.indexOf('wdev'))?2001:1001,
          FUN.Hwid2TypeName(Record.hwid)+' offline',timLib.NowStamp());
        //console.log('Offline affect',affectNum);
        console.log('Bye '+FUN.Hwid2TypeName(Record.hwid)+':',parseInt(Record.hwid),TimStr);
      })

      //如果是网关设备，清理所有子节点
      if(Record.hwtype == CFG.HwType.indexOf('gw'))
      {
        tbDevice.findByConnId(Hwid).then(Rcds=>{
          Rcds.some((one)=>{
            rCache.del(rCache.N_Config,one.hwid);//删除配置记录
            tbDevice.offline(one.hwid,one.hwtype==CFG.HwType.indexOf('wdev')?true:false).then((affectNum)=>{//wdev保留conn id
              tbLog.newDevLog(one.uid,one.hwid,
                one.hwtype==CFG.HwType.indexOf('wdev')?2001:1001,
                FUN.Hwid2TypeName(one.hwid)+' offline',timLib.NowStamp());
              //console.log('Offline affect',affectNum);
              console.log('Bye '+FUN.Hwid2TypeName(one.hwid)+':',parseInt(one.hwid),TimStr);
            })//end offline
          })//end some
        })//end findByConnId
      }
    } else {
      console.log('Not found:',Hwid);
    }
  })
}

//设备登记处理
//供host通过son config登记wdev使用
//ParentRcd为gw在数据表dev中的记录
function Son_Touch(Hwid,ParentRcd,brother=0)
{
  tbDevice.find(Hwid).then((Record)=>{
    if(Record)
    {
      if(Record.conn_id!=ParentRcd.hwid)
        tbDevice.updateDev(Hwid, {conn_id:ParentRcd.hwid});

      if(Record.project!=ParentRcd.project)
        tbDevice.updateDev(Hwid,  {project:ParentRcd.project});
    }
    else //数据库没有本设备记录，则新增记录
    {
      tbLog.newDevLog(0,Hwid,1003,'wdev unreg',timLib.NowStamp());
      console.log('Unreg1 WDev:',Hwid,timLib.NowStr());
    }
  })//end find
}

function Son_Online(Hwid,ParentRcd,brother=0)
{
  let TimStr=timLib.NowStr();
  let TypeName=FUN.Hwid2TypeName(Hwid);

  if(TypeName!=CFG.T_Wdev) return;

  tbDevice.find(Hwid).then((Record)=>{
    if(Record) //有本设备的记录
    {
      if(Record.conn_id && Record.conn_id!=ParentRcd.hwid)//本次上线经过的主机，和过往的不同
        console.log('[%d] Changed Host ??? [%d]->[%d]',Hwid,Record.conn_id,ParentRcd.hwid);

      tbDevice.online(Hwid,ParentRcd.ip,ParentRcd.hwid);
      tbLog.newDevLog(Record.uid,Hwid,2000,'wdev online',timLib.NowStamp());
      DevExpireHandler(Record);

      //if(Record.project!=ParentRcd.project) dbDev.updateDev(Hwid, {project:ParentRcd.project});

      let config={'uid':Record.uid,'hwid':Hwid,'brother':brother,'expire':timLib.Str2Stamp(Record.expire),'mode':Record.mode};
      rCache.set(rCache.N_Config,Hwid,config);//记录过期日期到缓存中

      console.log('Online Son:',parseInt(Hwid),TimStr);
    }
    else //数据库没有本设备记录
    {
      tbLog.newDevLog(0,Hwid,1003,'wdev unreg',timLib.NowStamp());
      console.log('Unreg2 WDev:',Hwid,timLib.NowStr());
    }
  })//end find
}

//网关的son config上报处理
function Mq_SonConfig(Parent,Devs)
{
  //查询所属网关
  tbDevice.find(Parent).then((Record)=>{
    if(Record==null) return;//数据库没有网关记录
    Devs.some((one)=>{//存储子设备
      if(one.on==0) Son_Touch(one.id,Record,one.br);//不在线的
      else Son_Online(one.id,Record,one.br);//在线的

      //设置兄弟信息到数据库
      tbDevice.find(one.id).then((Record)=>{
        if(Record && Record.brother!=one.br){
          tbDevice.updateDev(one.id, {brother:one.br}).then((affected)=>{
            if(affected) console.log('[%d] save brother ok',one.id);
          })
        }
      })//end find one.id

    })//end some
  })//end find parent
}

//wdev online消息处理，设置online标志
function Mq_WDevOnline(Hwid)
{
  let TimStr=timLib.NowStr();
  tbDevice.find(Hwid).then((Record)=>{
    if(Record==null) return;//数据库没有设备记录

    tbDevice.online(Hwid,Record.ip,Record.conn_id);
    tbLog.newDevLog(Record.uid,Hwid,1000,'wdev online',timLib.NowStamp());
    DevExpireHandler(Record);

    let config={'hwid':Hwid,'brother':Record.brother,'expire':timLib.Str2Stamp(Record.expire),'mode':Record.mode};
    rCache.set(rCache.N_Config,Hwid,config);//记录过期日期到缓存中

    console.log('Online WDev:',parseInt(Hwid),TimStr);
  })//end find
}

//wdev offline消息处理，设置online标志，保留conn_id(host id)
function Mq_WDevOffline(Hwid)
{
  tbDevice.find(Hwid).then((Record)=>{
    if(Record==null) return;//数据库没有设备记录
    tbDevice.offline(Hwid,true).then((affectNum)=>{
      tbLog.newDevLog(Record.uid,Hwid,1001,'wdev offline',timLib.NowStamp());
      console.log('Bye WDev:',parseInt(Hwid),timLib.NowStr());
    })
  })//end find
}

exports.Init=Init;
exports.Dev_Online=Dev_Online;
exports.Dev_Offline=Dev_Offline;
exports.Mq_SonConfig=Mq_SonConfig;
exports.Mq_WDevOnline=Mq_WDevOnline;
exports.Mq_WDevOffline=Mq_WDevOffline;